package org.mtmi.ui.scenes;

import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.mtmi.ui.M;
import org.mtmi.ui.actions.IAction;
import org.mtmi.ui.actions.RetargetableAction;
import org.mtmi.ui.controls.Control;
import org.mtmi.ui.controls.IContentProvider;
import org.mtmi.ui.controls.ListView;
import org.mtmi.ui.controls.listeners.ISelectionListener;
import org.mtmi.ui.controls.listeners.SelectionEvent;
import org.mtmi.ui.controls.popups.AbstractButtonPopup;
import org.mtmi.ui.drawables.IDrawable;

/**
 * Popup displaying a list of action available to create a SideButton.<br>
 *
 */
public class ChooseSideButtonActionPopup extends AbstractButtonPopup implements  ISelectionListener
{
	
	private class ContentProvider implements IContentProvider
	{
		@Override
		public Object[] getElements(Object input) {
			return SideButtonActionFactory.getDefault().getActionIds();
		}
	}
	
	private ListView lv_items;
	//private Item  items[];
	private IAction  selected;
	
	public ChooseSideButtonActionPopup( Scene scene, int flags ) {
		super(scene, "Choose Action:", flags);
	}
	
	@Override
	public Rectangle createContents( Scene _scene )
	{
		lv_items = new ListView( scene, M.SCENE_EDITOR_CONTROL );
		lv_items.addSelectionListener( this );
		lv_items.setLabelProvider( SideButtonActionFactory.getDefault() );
		lv_items.setContentProvider( new ContentProvider() );
		lv_items.setInput( this );
		
		Point s = scene.getSize();
		int w = s.x/3;
		int h = s.y/2;
		int x = (s.x-w)/2;
		int y = (s.y-h)/2;
		lv_items.setBounds( x, y, w, h );
		
		return new Rectangle( x, y, w, h );
	}
	
	public IAction getSelectedAction() {
		return selected;
	}
	
	@Override
	protected void terminate( int id ) {
		lv_items.dispose();
		super.terminate( id );
	}
	
	@Override
	public void selectionChanged( SelectionEvent e ) {
		selected = (IAction)e.selection;
	}

	@Override
	public void selectionConfirmed(SelectionEvent e) {
		selected = (IAction)e.selection;
		terminate( OK );
	}
	
//TODO: remove it if unused	
	private abstract static class CreateControl extends RetargetableAction
	{
		private IDrawable image;
		private String text;
		public CreateControl( String txt, IDrawable img ) {
			super( PUSH, null );
			image = img;
			text = txt;
		}
		@Override
		public IDrawable getImage() { return image; }
		@Override
		public String getText() { return text; }
		@Override
		public final void run() {
			Scene scene = (Scene)getTarget();
			Control c = createControl( scene );
			target = c;
		}
		protected abstract Control createControl( Scene scene );
	}
	
}
